package com.example.demo.controller;

import com.example.demo.common.Result;
import com.example.demo.entity.User;
import com.example.demo.param.LoginParam;
import com.example.demo.param.RegisterParam;
import com.example.demo.service.UserService;
import com.example.demo.vo.LoginVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * 认证控制器
 * 
 * @author zhang
 * @date 2024
 */
@RestController
@RequestMapping("/api/auth")
public class AuthController {
    
    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);
    
    @Autowired
    private UserService userService;
    
    /**
     * 用户登录
     * 异常由GlobalExceptionHandler自动捕获并封装到Result
     */
    @PostMapping("/login")
    public Result<LoginVO> login(@Valid @RequestBody LoginParam param) {
        logger.info("用户登录: {}", param.getUsername());
        LoginVO vo = userService.login(param.getUsername(), param.getPassword());
        return Result.create(vo);
    }
    
    /**
     * 用户注册
     * 异常由GlobalExceptionHandler自动捕获并封装到Result
     */
    @PostMapping("/register")
    public Result<LoginVO> register(@Valid @RequestBody RegisterParam param) {
        logger.info("用户注册: {}", param.getUsername());
        // 将RegisterParam转换为User
        User user = new User();
        user.setUsername(param.getUsername());
        user.setPassword(param.getPassword());
        user.setNickname(param.getNickname());
        user.setEmail(param.getEmail());
        user.setPhone(param.getPhone());
        
        LoginVO vo = userService.register(user);
        logger.info("用户注册成功: {}", param.getUsername());
        return Result.create(vo);
    }
}

